package com.asm.client;

import com.asm.message.*;
import com.asm.protocol.MessageCodecSharable;
import com.asm.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;


@Slf4j
public class ChatClient {
    public static void main(String[] args) {

        NioEventLoopGroup group = new NioEventLoopGroup();
        // 局部变量
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
       // LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        /**
         * CountDownLatch 是一个计数器，当值为0时，可以唤醒线程继续向下运行
         */
        // 倒计时锁，【主次线程之间 通信】
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);// 初始基数1，减为零才继续往下运行，否则等待
        // 登录状态 初始值 false 【主次线程之间 共享变量】
        AtomicBoolean LOGIN = new AtomicBoolean(false);
          AtomicBoolean EXIT = new AtomicBoolean(false);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // 帧解码器 【与自定义编解码器 MessageCodecSharable一起配置参数】
                    ch.pipeline().addLast(new ProcotolFrameDecoder());//只有入站
                    // 日志
                    //  ch.pipeline().addLast(LOGGING_HANDLER);
                    // 出站入站的 自定义编解码器 【 解析消息类型 】
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    /**@ClassName IdleStateHandler
                     * 用来判断是不是 读空闲时间过长，或写空闲时间过长
                    如果8秒没有向服务器写数据，会触发一个 IdleState.WRITE_IDLE事件*/

                    ch.pipeline().addLast(new IdleStateHandler(0, 8, 0));
                    //ChannelDuplexHandler可以同时作为出入站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        //用来触发特殊事件

                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            //如果两者相等，触发了写空闲事件
                            if (event.state() == IdleState.WRITER_IDLE) {
                                 // log.debug("已经8秒没有发送数据了，发送一个心跳包");
                                //发送心跳包
                            ctx.writeAndFlush(new PongMessage());
                            }
                        }
                    });

                    //登录服务器
                    ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {


                        //接收响应消息
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                           // log.debug("msg{}", msg);
                             //接收服务器返回过来的消息，判断是否用户名和密码输入正确
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage response = (LoginResponseMessage) msg;
                                if (response.isSuccess()) {
                                    //如果登录成功
                                    LOGIN.set(true);

                                }

                            }
                            //接收单聊消息
                            if (msg instanceof ChatResponseMessage) {
                                ChatResponseMessage response = (ChatResponseMessage) msg;
                               // System.out.println(response.getFrom());
                                System.out.println(response.getContent()+"----单聊消息");
                            }

                            //接收群聊消息
                            if(msg instanceof GroupChatResponseMessage){
                                GroupChatResponseMessage response = (GroupChatResponseMessage) msg;

                                System.out.println(response.getContent()+"-----接收消息内容");
                            }

                               //倒计时唤醒一个线程
                            WAIT_FOR_LOGIN.countDown();
                        }

                        //入站触发
                        // 在连接建立后会触发
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            //负责接收用户在控制台的输入，负责向服务器发送各种数据
                            new Thread(() -> {
                                Scanner sc = new Scanner(System.in);
                                System.out.println("请输入用户名");
                                String userName = sc.nextLine();
                                System.out.println("请输入密码");
                                String passWord = sc.nextLine();
                                //构造消息对象
                                LoginRequestMessage message = new LoginRequestMessage(userName, passWord);
                                //发送消息
                                ctx.writeAndFlush(message);
                                System.out.println("等待后续操作");


                                try {
                                    //等待
                                    WAIT_FOR_LOGIN.await();// 减一 唤醒 线程：system in
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                //如果登录失败
                                if (!LOGIN.get()) {
                                    ctx.channel().close();
                                    return;
                                }
                                while (true) {
                                    System.out.println("============ 功能菜单 ============");
                                    System.out.println("send [username] [content],发送聊天信息");  //发送聊天信息
                                    System.out.println("gsend [group name] [content],向一个聊天组发送信息");  //向一个聊天组发送信息
                                    System.out.println("gceate [group name] [m1,m2,m3...],创建一个聊天群组"); //创建一个聊天群组
                                    System.out.println("gmembers [group name],获取群组成员 "); //获取群组成员
                                    System.out.println("gjoin [group name],加入聊天组");  //加入聊天组
                                    System.out.println("gquit [username],退出聊天组");  //获取聊天组
                                    System.out.println("quit,退出");  //退出
                                    System.out.println("==============================");
                                    String command = sc.nextLine();
                                    String[] s = command.split(" ");

                                    switch (s[0]) {
                                        case "send":

                                            ctx.writeAndFlush(new ChatRequestMessage(userName, s[1], s[2]));

                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GroupChatRequestMessage(userName, s[1], s[2]));
                                            break;
                                        case "gceate":
                                            //把数组变成集合
                                            Set<String> list = new HashSet<>(Arrays.asList(s[2].split(",")));
                                              list.add(userName);//加入自己
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], list));
                                            break;
                                        case "gmembers":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(userName, s[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(s[1],userName));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }

                                }


                            }, "system in").start();
                        }

                        // 在连接断开时触发
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("Client...主动-连接已经断开，按任意键退出..");

                           EXIT.set(true);


                        }

                        // 在出现异常时触发
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.debug("Client...异常-连接已经断开，按任意键退出..{}", cause.getMessage());
                            EXIT.set(true);
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }


}
